package com.qingmu.club.minaapi.controller.member;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingmu.club.minaapi.custom.logic.ClubUsersLogic;
import com.qingmu.club.minaapi.model.MiniLoginModel;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.custom.logic.UsersWxLogic;
import com.qingmu.club.minaapi.plus.service.ClubUsersService;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.*;
import com.qingmu.club.minaapi.wechat.WechatUtil;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 会员微信资料 前端控制器
 * </p>
 *
 * @author duke
 * @since 2019-08-20
 */
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "会员信息(会员端小程序)", description = "会员信息(会员端小程序)")
@RequestMapping("/member/users")
public class MemberUserController {

    @Autowired
    UsersWxLogic usersWxLogic;

    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    ClubStaffService clubStaffService;

    @Autowired
    ClubShopService clubShopService;

    @Autowired
    ClubStaffShopService clubStaffShopService;

    @Autowired
    UsersService usersService;

    @Autowired
    ClubUsersLogic clubUsersLogic;

    @RequestMapping(value = "/queryClubUsersShopList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "查询会员关注的门店列表")
    public ResponseEntity queryClubUsersShopList(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId
    ) {
        Users users = this.usersService.getById(userId);
        if (users == null) {
            return ResponseObject.error(401, "会员信息找不到");
        }
        List<ClubShop> attentionShopList =this.clubUsersLogic.queryUserAttentionShop(userId);
        return ResponseObject.success(attentionShopList);
    }

    @RequestMapping(value = "/queryClubUsers", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "查询会员信息")
    public ResponseEntity queryClubUsers(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId
    ) {
        Users users = this.usersService.getById(userId);
        if (users == null) {
            return ResponseObject.error(401, "会员信息找不到");
        }
        ClubUsers clubUsers = this.clubUsersLogic.getUserShop(shopId, userId);
        if(clubUsers==null){
            return ResponseObject.error(556,"会员暂未关注该门店");
        }
        return ResponseObject.success(clubUsers);
    }


    @RequestMapping(value = "/updateClubUsers", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "修改会员信息")
    public ResponseEntity updateClubUsers(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = false, value = "孩子姓名") @RequestParam(required = false) String sonName,
            @ApiParam(required = false, value = "孩子生日") @RequestParam(required = false) String sonDate,
            @ApiParam(required = false, value = "所在省代码") @RequestParam(required = false) String province,
            @ApiParam(required = false, value = "所在市代码") @RequestParam(required = false) String city,
            @ApiParam(required = false, value = "所在区代码") @RequestParam(required = false) String area,
            @ApiParam(required = false, value = "所在省名称") @RequestParam(required = false) String provinceText,
            @ApiParam(required = false, value = "所在市名称") @RequestParam(required = false) String cityText,
            @ApiParam(required = false, value = "所在区名称") @RequestParam(required = false) String areaText,
            @ApiParam(required = false, value = "详细地址") @RequestParam(required = false) String address,
            @ApiParam(required = false, value = "学校") @RequestParam(required = false) String sonSchool
    ) {
        Users users = this.usersService.getById(userId);
        if (users == null) {
            return ResponseObject.error(401, "会员信息找不到");
        }
        ClubUsers clubUsers = this.clubUsersLogic.getUserShop(shopId, userId);
        if(clubUsers==null){
            return ResponseObject.error(556,"会员暂未关注该门店");
        }
        if (!StringUtils.isEmpty(sonName))clubUsers.setSonName(sonName);
        if (!StringUtils.isEmpty(sonDate))clubUsers.setSonDate(sonDate);
        if (!StringUtils.isEmpty(province))clubUsers.setProvince(province);
        if (!StringUtils.isEmpty(city)) clubUsers.setCity(city);
        if (!StringUtils.isEmpty(area)) clubUsers.setArea(area);
        if (!StringUtils.isEmpty(address))clubUsers.setAddress(address);
        if (!StringUtils.isEmpty(sonSchool))clubUsers.setSonSchool(sonSchool);
        if (!StringUtils.isEmpty(provinceText))clubUsers.setProvinceText(provinceText);
        if (!StringUtils.isEmpty(cityText)) clubUsers.setCityText(cityText);
        if (!StringUtils.isEmpty(areaText)) clubUsers.setAreaText(areaText);
        boolean state =this.clubUsersService.updateById(clubUsers);
        if (!state) {
            return ResponseObject.error();
        }
        return ResponseObject.success();
    }




    @RequestMapping(value = "/queryStaffShop", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "查询教练绑定的门店信息")
    public ResponseEntity queryStaffShop(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "教练关联门店id") @RequestParam(required = true) String staffShopId
    ) {
        Users users = this.usersService.getById(userId);
        if (users == null) {
            return ResponseObject.error(401, "会员信息找不到");
        }
        ClubStaffShop clubStaffShop =this.clubStaffShopService.getById(staffShopId);
        if(clubStaffShop==null){
            return ResponseObject.error(556,"人员信息出错 请联系管理员");
        }
        return ResponseObject.success(clubStaffShop);
    }
    @RequestMapping(value = "/bindingCoach", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "用户扫描二维码 绑定教练")
    public ResponseEntity bindingCoach(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "教练关联门店id") @RequestParam(required = true) String staffShopId
    ) {
        Users users = this.usersService.getById(userId);
        if(users==null){
            return ResponseObject.error(401,"会员信息找不到");
        }

        if(StringUtils.isEmpty(users.getUserName()) && StringUtils.isEmpty(users.getUserSex()) && StringUtils.isEmpty(users.getUserIcon())){
            return ResponseObject.error(408,"请授权会员信息");
        }

        ClubStaffShop clubStaffShop =this.clubStaffShopService.getById(staffShopId);
        if(clubStaffShop==null){
            return ResponseObject.error(556,"人员信息出错 请联系管理员");
        }
        String shopId = clubStaffShop.getShopId();
        String coachId = clubStaffShop.getStaffId();


        ClubStaff clubStaff = this.clubStaffService.getById(coachId);
        ClubShop clubShop =this.clubShopService.getById(shopId);
        //如果会员已经关注该门店 那么直接返回成功
        QueryWrapper<ClubUsers> clubUsersQueryWrapper = new QueryWrapper<>();
        clubUsersQueryWrapper.eq(ClubUsers.SHOP_ID,shopId).eq(ClubUsers.USER_ID,userId);
        ClubUsers oneClubUsers  =this.clubUsersService.getOne(clubUsersQueryWrapper);
        if(oneClubUsers!=null) {
            //归属教练信息
            oneClubUsers.setAffiliationCoach(coachId);
            oneClubUsers.setAffiliationCoachAvater(clubStaff.getAvatar());
            oneClubUsers.setAffiliationCoachName(clubStaff.getStaffName());
            oneClubUsers.setStatus(KeyValueDefine.ONLINE_STATUS);//默认启用
            oneClubUsers.setAttentionType(KeyValueDefine.ATTENTION_COACH);//关注教练
            boolean state = this.clubUsersService.updateById(oneClubUsers);
            if (!state) {
                return ResponseObject.error();
            }
            return ResponseObject.success();
        }

        ClubUsers newClubUsers = new ClubUsers();
        newClubUsers.setUserId(users.getId());
        newClubUsers.setUserName(users.getUserName());
        newClubUsers.setUserSex(users.getUserSex());
        newClubUsers.setClubId(clubShop.getClubId());
        //归属教练信息
        newClubUsers.setAffiliationCoach(coachId);
        newClubUsers.setAffiliationCoachAvater(clubStaff.getAvatar());
        newClubUsers.setAffiliationCoachName(clubStaff.getStaffName());
        //门店信息
        newClubUsers.setShopId(shopId);
        newClubUsers.setShopName(clubShop.getShopName());
        newClubUsers.setShopAvater(clubShop.getCover1());

        newClubUsers.setAttentionTime(new Date());
        newClubUsers.setAttentionStatus(KeyValueDefine.ATTENTION);
        newClubUsers.setUserShowStatus(KeyValueDefine.LATENT);//潜在学员
        newClubUsers.setUserIcon(users.getUserIcon());
        oneClubUsers.setStatus(KeyValueDefine.ONLINE_STATUS);//默认启用
        oneClubUsers.setAttentionType(KeyValueDefine.ATTENTION_COACH);//关注教练
        newClubUsers.setUserMobile(users.getUserMobile());
        boolean state = this.clubUsersService.save(newClubUsers);
        if (!state) {
            return ResponseObject.error();
        }

        return ResponseObject.success();

    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "修改用户信息")
    public ResponseEntity update(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = false, value = "用户性别") @RequestParam(required = false) String userSex,
            @ApiParam(required = false, value = "用户头像") @RequestParam(required = false) String userIcon,
            @ApiParam(required = false, value = "用户昵称") @RequestParam(required = false) String userName,
            @ApiParam(required = false, value = "用户生日") @RequestParam(required = false) String birthDate,
            HttpServletRequest request
    ) {
        Users users  = this.usersService.getById(userId);
        if(users==null){
            return ResponseObject.error(401,"用户不存在");
        }

        users.setUserSex(userSex);
        users.setUserIcon(userIcon);
        users.setUserName(userName);
        users.setBirthDate(birthDate);

        boolean state = this.usersService.updateById(users);

        if(!state){
            return ResponseObject.error();
        }
        
        return ResponseObject.success(this.usersService.getById(userId));
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "小程序授权获取手机号")
    public ResponseEntity login(
            @RequestBody(required = true) MiniLoginModel miniLoginModel,
            HttpServletRequest request
    ) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

            url = String.format(url, WechatUtil.memberAppId, WechatUtil.memberAppSecret, miniLoginModel.getCode());
            String content = HttpUtils.requestGet(url, null, null);

            if (content == null) {
                return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"解密失败");
            }

            HashMap<String, Object> returnMap = Utils.stringToMap(content);
            String openid = (String) returnMap.get("openid");
            String session_key = (String) returnMap.get("session_key");
            if (StringUtils.isEmpty(openid)) {
                return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"openid获取失败");
            }

            String result = Utils.decrypt(miniLoginModel.getEncryptedData(), session_key, miniLoginModel.getIv(), "UTF-8");
            if (StringUtils.isEmpty(result)) {
                return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"解密失败");
            }

            HashMap<String, Object> hashMap = ConvertUtil.stringToMap(result);
            String staffMobile = (String) hashMap.get("phoneNumber");

            Users users = this.usersWxLogic.loginByMobile(openid,staffMobile);

            return ResponseObject.success(users);

        } catch (Exception e) {
            e.printStackTrace();
            LoggerFactory.getLogger(this.getClass()).error(e.getMessage());
            return ResponseObject.error(ResponseObject.ResponseCode_SYS_ERROR,"系统繁忙");
        }
    }

    @RequestMapping(value = "/loginGetUserInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "小程序授权用户信息登录")
    public ResponseEntity loginGetUserInfo(
            @RequestBody(required = true) MiniLoginModel miniLoginModel,
            HttpServletRequest request
    ) {
        try {

            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

            url = String.format(url, WechatUtil.memberAppId, WechatUtil.memberAppSecret, miniLoginModel.getCode());
            String content = HttpUtils.requestGet(url, null, null);

            if (content == null) {
                return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"解密失败");
            }

            HashMap<String, Object> returnMap = Utils.stringToMap(content);

            String openid = (String) returnMap.get("openid");
            String session_key = (String) returnMap.get("session_key");

            if (StringUtils.isEmpty(openid)) {

              return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"openid获取失败");

            }

            String result = Utils.decrypt(miniLoginModel.getEncryptedData(), session_key, miniLoginModel.getIv(), "UTF-8");

            if (StringUtils.isEmpty(result)) {

                return ResponseObject.error(ResponseObject.ResponseCode_NOT_FOUNDED,"解密失败");
            }

            JSONObject userInfoJSON = JSONObject.fromObject(result);

            String sex = "";
            if (1 == (int) userInfoJSON.get("gender")) {
                sex="male";
            } else if (2 == (int) userInfoJSON.get("gender")) {
                sex="female";
            } else {
                sex = "none";
            }

            String nikeName = EmojiParser.removeAllEmojis(userInfoJSON.getString("nickName"));
            String userIcon = userInfoJSON.getString("avatarUrl");
            Users users = this.usersWxLogic.addUserInfo(nikeName,userIcon,sex,miniLoginModel.getUserId());

            return ResponseObject.success(users);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerFactory.getLogger(this.getClass()).error(e.getMessage());
            return ResponseObject.error(ResponseObject.ResponseCode_SYS_ERROR,"系统错误请联系管理员");
        }
    }


}

